package com.tsky.system.manager.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.tsky.casing.QueryBean;
import com.tsky.casing.orm.impl.EntityManagerImpl;
import com.tsky.common.BeanUtil;
import com.tsky.system.entity.Role;
import com.tsky.system.manager.RoleManager;
import com.tsky.system.query.RoleQuery;

@Repository("roleManager")
public class RoleManagerImpl extends EntityManagerImpl implements RoleManager {

	public void query(QueryBean queryBean) {
		// TODO Auto-generated method stub
		RoleQuery query = (RoleQuery) queryBean;
		
		// 基本查询条件
		int page = queryBean.getPage();
		int pageSize = queryBean.getRows(); // page size
		String orderField = queryBean.getSort();
		String sortOrder = queryBean.getOrder();
		
		// 组合查询条件
		String name = query.getName();
		String status = query.getStatus();
		String description = query.getDescription();
		
		Criteria ctr = this.getSession().createCriteria(Role.class);

		// 组合查询
		if (!BeanUtil.isEmpty(status) && !"3".equals(status)) {
			ctr.add(Restrictions.eq("status", status));
		}
		
		if (!BeanUtil.isEmpty(name)) {
			ctr.add(Restrictions.like("name", "%" + name + "%"));
		}
		
		if (!BeanUtil.isEmpty(description)) {
			ctr.add(Restrictions.like("description", "%" + description + "%"));
		}
		
		// 排序
		if (!BeanUtil.isEmpty(sortOrder)) {
			if ("asc".equals(sortOrder)) {
				ctr.addOrder(Order.asc(orderField));
			} else {
				ctr.addOrder(Order.desc(orderField));
			}
		}

		// 总记录数
		List<?> resultList = ctr.list();
		queryBean.setTotal(resultList.size());

		ctr.setFirstResult(pageSize * (page - 1));
		ctr.setMaxResults(pageSize);
		
		queryBean.setDataList(ctr.list());
	}
	
}
